﻿IF EXISTS (
    SELECT
      1
    FROM sysobjects
    WHERE id = OBJECT_ID('bd_proc_seal_calc_dayoff')
      AND type IN ('P', 'PC')
  )
  DROP PROCEDURE bd_proc_seal_calc_dayoff

GO

-- =============================================
-- Author:      YFC
-- Create date: 2020-07-27 12:01:26
-- Database:    [scm_main-hysj2]
-- Description: 考勤管理-HR考勤封账后处理时间银行调休假
-- =============================================

CREATE PROCEDURE bd_proc_seal_calc_dayoff
  @settleYear INT,
  @settleMonth  INT,
  @userJson VARCHAR(MAX),
  @optype INT,  --1：封账  2：解封
  @operateId  BIGINT
AS
BEGIN
  SET NOCOUNT ON;

  SELECT * INTO #user FROM OPENJSON(@userJson) WITH (
    user_serial BIGINT,
    day_off_before  INT,
    day_off_after INT)


  DECLARE @now DATETIME = GETDATE()

  IF @optype = 1 
  BEGIN  
    --更新前调休额度
    UPDATE u
    SET day_off_before = ht.rest_total
    FROM #user u
    INNER JOIN (
        SELECT
          user_serial, rest_total
        FROM bd_view_kq_holidays_time_rowno
        WHERE row_no = 2
      ) ht ON ht.user_serial = u.user_serial
  
    --更新后调休额度
    UPDATE u
    SET day_off_after = ht.rest_total
    FROM #user u
    INNER JOIN (
        SELECT
          user_serial, rest_total
        FROM bd_view_kq_holidays_time_rowno
        WHERE row_no = 1
      ) ht ON ht.user_serial = u.user_serial  	

  
    INSERT INTO dbo.bd_kq_holidays(user_serial
    , dept_serial
    , dept_name
    , ho_year
    , ho_month
    , ho_date
    , ho_type
    , deduct_before
    , deduct_usage
    , deduct_remain
    , related_id
    , create_id
    , create_time)
    SELECT ud.user_serial, u.user_dep, u.dep_name, YEAR(@now), MONTH(@now), @now, 12, ISNULL(day_off_before, 0), 
      ISNULL(day_off_after, 0) - ISNULL(day_off_before, 0), ISNULL(day_off_after, 0), 0, @operateId, GETDATE()
    FROM #user ud
    INNER JOIN bd_view_user_all u ON u.user_serial = ud.user_serial  
  END
  ELSE
  BEGIN
    UPDATE u
    SET day_off_before = ht.rest_total
    FROM #user u
    INNER JOIN (
        SELECT
          user_serial, rest_total
        FROM bd_view_kq_holidays_time_rowno
        WHERE row_no = 1
      ) ht ON ht.user_serial = u.user_serial

    INSERT INTO dbo.bd_kq_holidays(user_serial
    , dept_serial
    , dept_name
    , ho_year
    , ho_month
    , ho_date
    , ho_type
    , deduct_before
    , deduct_usage
    , deduct_remain
    , related_id
    , create_id
    , create_time)
    SELECT ud.user_serial, u.user_dep, u.dep_name, YEAR(@now), MONTH(@now), @now, 13, ISNULL(day_off_before, 0), 
      ISNULL(day_off_before, 0), 0, 0, @operateId, GETDATE()
    FROM #user ud
    INNER JOIN bd_view_user_all u ON u.user_serial = ud.user_serial  
  END

  SET NOCOUNT OFF;
END